<template>
  <!-- 富文本 -->
  <div style="width: 700px; margin: 0 auto">
    <div style="margin: 10px">
      <button style="width: 49%" @click="saveModify">保存内容</button>
      <button style="width: 49%" @click="exportWord">导出word</button>
    </div>
    <editor
      id="tinymce"
      v-model="content"
      :init="init"
      :disabled="disabled"
      @onClick="onClick"
      @click="firstClick"
    ></editor>
  </div>
</template>

<script>
//引入jQuery和导出Word的JS文件
import $ from "jquery";
require("../assets/js/jquery.wordexport");
// 汉化
import { zh_CN } from "../assets/js/zh_CN";
// 引入编辑器
import tinymce from "tinymce/tinymce";
import Editor from "@tinymce/tinymce-vue";
//引入工具栏图标和主题
import "tinymce/themes/silver/theme";
import "tinymce/icons/default/icons";
import "tinymce/themes/silver";

// 扩展插件
import "tinymce/plugins/image";
import "tinymce/plugins/media";
import "tinymce/plugins/table";
import "tinymce/plugins/lists";
import "tinymce/plugins/contextmenu";
import "tinymce/plugins/wordcount";
import "tinymce/plugins/colorpicker";
import "tinymce/plugins/textcolor";
import "tinymce/plugins/preview";
import "tinymce/plugins/code";
import "tinymce/plugins/advlist";
import "tinymce/plugins/codesample";
import "tinymce/plugins/hr";
import "tinymce/plugins/fullscreen";
import "tinymce/plugins/textpattern";
import "tinymce/plugins/searchreplace";
import "tinymce/plugins/autolink";
import "tinymce/plugins/directionality";
import "tinymce/plugins/visualblocks";
import "tinymce/plugins/visualchars";
import "tinymce/plugins/template";
import "tinymce/plugins/charmap";
import "tinymce/plugins/nonbreaking";
import "tinymce/plugins/insertdatetime";
import "tinymce/plugins/autosave";
import "tinymce/plugins/autoresize";
// 保存
import "tinymce/plugins/save";
// 上传图片的插件
import "tinymce/plugins/imagetools";
// 上传文件的插件
import "tinymce/plugins/link";
// 导入word插件
import "/public/static/tinymce/importword";
//不可编辑元素
import "tinymce/plugins/noneditable";
// 打印
import "tinymce/plugins/print";
export default {
  components: {
    Editor,
  },
  props: {
    //从后台获取的字符串HTML数据，
    value: {
      type: String,
      default: "",
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    //使用的插件
    plugins: {
      type: [String, Array],
      default:
        "save print paste noneditable preview searchreplace autolink directionality visualblocks visualchars fullscreen image link media template code codesample table charmap hr nonbreaking insertdatetime advlist lists wordcount imagetools textpattern autosave bdmap autoresize lineheight importword",
    },
    //工具栏
    toolbar: {
      type: [String, Array],
      default:
        "importword template print save code undo redo restoredraft cut copy paste pastetext | forecolor backcolor bold italic underline strikethrough link codesample alignleft aligncenter alignright alignjustify outdent indent lineheight formatpainter | \
    styleselect formatselect fontselect fontsizeselect | bullist numlist | blockquote subscript superscript removeformat | \
    table image media charmap hr pagebreak insertdatetime | bdmap fullscreen preview",
    },
  },
  data() {
    return {
      //初始化配置
      init: {
        selector: "#tinymce",
        language_url: "static/tinymce/langs/zh-Hans.js",
        language: "zh_CN",
        skin_url: "/static/tinymce/skins/ui/oxide",
        object_resizing: false, // 图片和表格是否开启在编辑器内部缩放
        paste_data_images: true, // 粘贴的同时能把内容里的图片自动上传，非常强力的功能
        paste_convert_word_fake_lists: false, // 插入word文档需要该属性
        paste_webkit_styles: "all", //此选项允许您指定在WebKit中粘贴时要保留的样式
        paste_merge_formats: true, //此选项启用粘贴插件的合并格式功能
        theme_advanced_buttons3_add: "pastetext,pasteword,selectall",
        nonbreaking_force_tab: true, //不间断空格
        templates: [
          {
            title: "工程临时 / 最终延期报审表",
            description: "工程临时 / 最终延期报审表",
            url: "static/html/1.html",
          },
        ],
        height: 800,
        min_height: 800,
        max_height: 900,
        toolbar_mode: "wrap",
        plugins: this.plugins,
        toolbar: this.toolbar,
        content_style: "p {margin: 5px 0;}",
        fontsize_formats: "12px 14px 16px 18px 24px 36px 48px 56px 72px",
        font_formats:
          "微软雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC,sans-serif;苹果苹方=PingFang SC,Microsoft YaHei,sans-serif;宋体=simsun,serif;仿宋体=FangSong,serif;黑体=SimHei,sans-serif;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;",
        branding: false,
        save_enablewhendirty: false,
        save_onsavecallback: function () {
          console.log("已保存");
        },
        //此处为图片上传处理函数，这个直接用了base64的图片形式上传图片，
        //如需ajax上传可参考https://www.tiny.cloud/docs/configure/file-image-upload/#images_upload_handler
        images_upload_handler: (blobInfo, success) => {
          const img = "data:image/jpeg;base64," + blobInfo.base64();
          success(img);
        },
        // 上传文件
        file_picker_callback: function (callback, value, meta) {
          // 为链接对话框提供文件和文本
          if (meta.filetype == "file") {
            callback("mypage.html", { text: "My text" });
          }
          // 图片类型
          if (meta.filetype == "image") {
            callback("myimage.jpg", { alt: "My alt text" });
          }
          // 提供其他来源并张贴媒体对话
          if (meta.filetype == "media") {
            callback("movie.mp4", { source2: "alt.ogg", poster: "image.jpg" });
          }
        },
        init_instance_callback: function () {
          // console.log(editor.getContent());
        },
        // 预处理函数 importword_handler
        importword_handler: function (editor, files, next) {
          var file_name = files[0].name;
          // console.log(editor.getContent());
          if (file_name.substr(file_name.lastIndexOf(".") + 1) == "docx") {
            editor.notificationManager.open({
              text: "正在转换中...",
              type: "info",
              closeButton: false,
            });
            next(files);
          } else {
            editor.notificationManager.open({
              text: "目前仅支持docx文件格式，若为doc111，请将扩展名改为docx",
              type: "warning",
            });
          }
          // next(files);
        },
        // 过滤函数 importword_filter
        importword_filter: function (result, insert) {
          console.log(result);
          // 自定义操作部分
          insert(result); //回插函数
        },
      },
      content: this.value,
    };
  },
  mounted() {
    tinymce.init({});
    // 中文化
    tinymce.addI18n("zh_CN", zh_CN);
  },
  methods: {
    // 需要什么事件可以自己增加
    onClick(e) {
      this.$emit("onClick", e, tinymce);
    },
    // 点击
    firstClick() {
      // let textHtml = tinymce.editors[0].getContent();
      console.log(tinymce.editors[0].getContent());
    },
    // 可以添加一些自己的自定义事件，如清空内容
    clear() {
      this.content = "";
    },
    // 导出word
    exportWord() {
      setTimeout(function () {
        // 找到编辑框里面的dom对象
        console.log(tinymce.editors);
        var dom = tinymce.editors[0].contentDocument.documentElement;
        $(dom).wordExport("测试world");
      }, 300);
    },
    //保存内容
    saveModify() {
      //获取编辑器的内容，获取的是html，也就是包括标签和样式的内容。
      var content = tinymce.get("tinymce").getContent();
      //发送请求。。。
      console.log(content);
    },
    importWord() {},
  },
  watch: {
    value(newValue) {
      this.content = newValue;
    },
    content(newValue) {
      this.$emit("input", newValue);
    },
  },
};
</script>
<style></style>
